gpt4 book ai didi

c++ - 从指向具有 const 和非常量版本的成员函数的指针推导模板参数

转载 作者:太空宇宙 更新时间:2023-11-04 12:12:34 27 4
gpt4 key购买 nike

我有这样的代码:

#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]

很明显为什么编译器不知道该做什么。我的问题是,如果存在非 const 版本,如何调用具有 non-const exists 的版本,如果只有 const 版本,如何调用具有 const exists 的版本?

注意:对于这个问题,我假设没有常量版本就不能存在非常量版本。但是,如果您有针对更一般情况的解决方案,当您还可以区分非常量存在但常量不存在的情况时,我们也将不胜感激。

最佳答案

如此简单的解决方案(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++ - 从指向具有 const 和非常量版本的成员函数的指针推导模板参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9228839/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com