从指针到具有常量和非常量版本的成员函数的模板参数推导
Template argument deduction from pointer to member function with const and non-const versions
我有一个这样的代码:
#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;
}
它没有编译错误消息:
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版本就不可能存在。然而,如果您有一个更通用的情况的解决方案,当您可以区分非常量存在但常量不存在的情况时,也将不胜感激。
所以简单的解决方案(ideone):
#include <iostream>
struct Tester {
template <typename T, typename FT>
void operator()( const FT & (T::*ptr)() const ) const
{
std::cout << "const exists" << std::endl;
}
template <typename T, typename FT>
void operator()( 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 )
{
Tester t;
t(&A::a);
t(&B::b);
return 0;
}
相关文章:
- 常量函数,当其参数是对文字类型的引用时
- 为什么在C++使用常量函数时常量是多余的?
- 是否可以使用非常量指针调用非常量函数,以及当两个unique_ptrs指向同一个对象时程序的行为方式?
- 为什么在PIMPL中无法访问实现类的常量函数?
- 常量函数参数的专业化
- 如何调用非常量函数而不是常量函数?
- 常量和非常量函数作为模板参数参数
- 通过引用常量函数调用另一个类的非常量函数
- C++编译器如何检测非常量函数体
- 使用常量函数返回常量引用时出现奇怪的行为
- 常量字符数组模板与字符常量* 函数重载
- 现代C++编译器是否能够避免在某些条件下两次调用常量函数
- 将函数声明为 GCC 纯函数或常量函数的效果(当它不是时)
- 为什么常量/非常量函数重载的继承不明确
- 类型定义模板,接受指向常量和非常量函数的指针
- 如何避免语法相同的常量和非常量函数之间代码重复,这些函数在语义上不相同
- 继承的常量函数
- 不确定 c++ 中的常量函数是什么
- 在常量函数中使用安全的非常量函数
- c++如何定义其他开发人员需要调用的常量函数顺序