1
我有這樣的代碼:模板參數推導從指針與常量和非const版本的成員函數
#include <iostream>
template <typename T, typename FT>
void test(const FT & (T::*ptr)() const)
{
std::cout << "const exists" << std::endl;
}
template <typename T, typename FT>
void test(FT & (T::*ptr)())
{
std::cout << "non-const exists" << std::endl;
}
struct A {
const double & a() const { return a_; }
double & a() { return a_; }
private:
double a_;
};
struct B {
const double & b() const { return b_; }
private:
double b_;
};
int main(int argc, char **argv)
{
test(&A::a);
test(&B::b);
return 0;
}
不與error message編譯:
prog.cpp: In function ‘int main(int, char**)’:
prog.cpp:35: error: call of overloaded ‘test(<unresolved overloaded function type>)’ is ambiguous
prog.cpp:4: note: candidates are: void test(const FT& (T::*)()const) [with T = A, FT = double]
prog.cpp:10: note: void test(FT& (T::*)()) [with T = A, FT = double]
很清楚爲什麼編譯器不知道該怎麼做。 我的問題是如何調用non-const exists
如果有非常量版本和const exists
如果只有const版本?
注意:對於這個問題,我假定非const版本不能沒有const版本存在。然而,如果你有一個更一般的情況下的解決方案,當你可以區分的情況下,當非常量存在,但const不會它也將不勝感激。
我想你可能是出於運氣。 &A :: a沒有類型,因爲它是一個重載而不是函數。 – 2012-02-10 14:07:18