2017-10-19 68 views
3

这里是指针到接受两个整数并返回一个int一个类的方法:模板的typedef接受指针const和非const功能

template <typename T> 
using TFunction = int (T::*)(int, int); 

我只能通过这里非const方法。 如何改变这个模板,使它能接受const和非const方法?

+0

你的意思是* const *和non-'constst *函数,对吧?没有一个指针类型可以同时进行。 – Quentin

+0

我不接受*任何*会员。它接受一个'T'。你在[mcve]上做得太少了。这是一个XY问题。 – StoryTeller

+0

您不能同时指定2种类型的名称。你可以使用'template '使用TCFunction = int(T :: * const)(int,int);'为'const'函数命名或者用'std :: function'键入或擦除函数指针或者自己的版本。 – nwp

回答

6

这种情况是一个条件很简单:

template <typename T> 
using TFunction = std::conditional_t< 
    std::is_const_v<T>, 
    int (T::*)(int, int) const, 
    int (T::*)(int, int) 
>; 

现在TFunction<Foo>int (Foo::*)(int, int),而TFunction<Foo const>int (Foo::*)(int, int) const

+1

但是具有常数成员函数的非const Foo类型呢? – Jodocus

+1

@Jodocus这是一个红鲱鱼:我将''const'-or-non-'const'“参数捎带到'T'上,而不是使它成为一个单独的'bool'。它与你以后使用的实际'Foo'的'const'无关,你仍然可以调用'TFoo '到'Foo' :) – Quentin

+2

删除我原来的评论,因为这个是辉煌的。即使通常'T'必须是一个id表达式(因此通常不能是const T),模板上下文允许使用类型信息,*和*保持指向成员的指针形成。 – StoryTeller

相关问题