我正在尝试检测一个类是否具有特定的功能(具体来说shared_from_this(),是继承自哪个std::enable_shared_from_this<Some Unknown Class>).为了使事情变得更复杂,我需要知道它是否具有此功能,即使它已从远程基类继承或使用受保护访问继承.
我已经查看了其他问题,例如这个问题,但提供的方法不适用于检测受保护的成员函数.
我目前使用的方法如下:
template <class T>
struct shared_from_this_wrapper : public T
{
template <class U>
static auto check( U const & t ) -> decltype( t.shared_from_this(), std::true_type() );
static auto check( ... ) -> decltype( std::false_type() );
};
template<class T>
struct has_shared_from_this : decltype(shared_from_this_wrapper<T>::check(std::declval<shared_from_this_wrapper<T>>()))
{ };
Run Code Online (Sandbox Code Playgroud)
我当前解决方案的缺陷是它不适用于声明的类final.所以我正在寻找一个满足以下成员函数的测试解决方案:
final编辑:我有一个可行的解决方案,但需要与帮助类成为朋友,这也不是一个理想的解决方案,但现在可能是一种解决方法(因为它满足所有要求):
struct access
{
template <class T>
static auto shared_from_this( T const & t ) -> …Run Code Online (Sandbox Code Playgroud) 我刚刚升级到GCC 4.8,一些可变参数模板代码不再正确编译.我在下面创建了一个最小的示例:
#include <tuple>
#include <iostream>
template <class T, class ... OtherT>
void something( std::tuple<T, OtherT...> & tup )
{
std::cout << std::get<1>(tup) << std::endl;
}
int main()
{
std::tuple<int, char, bool> myTuple(3, 'a', true);
// Compiles OK in GCC 4.6.3 but NOT 4.8
something<int, char, bool>( myTuple );
// Compiles OK in GCC 4.8 but NOT 4.6.3
something<int, bool, char>( myTuple );
return 0;
}
Run Code Online (Sandbox Code Playgroud)
这个输出将是(如果注释掉GCC 4.6.3/4.8的错误版本)'a'.
GCC 4.6.3产生的错误是:
./test.cpp: In function ‘int main()’:
./test.cpp:18:39: error: no matching function …Run Code Online (Sandbox Code Playgroud) 我正在编写一些类型特征,以查看是否存在具有一组特定参数的自由函数.这些函数的签名看起来像这样:
template <class T> void func( SomeClass &, SomeType const & );
Run Code Online (Sandbox Code Playgroud)
我知道前面的时间值T,SomeClass和SomeType.如果此函数与这些参数完全相同,我希望特征返回true,而不是使用任何隐式转换.
我可以通过使用SFINAE尝试调用它来轻松编写一些代码来检测此函数是否存在,例如
// potentially in some namespace
template <class> void func(); // this is necessary since user implementations
// of func will not exist until after
// this has been defined
template <class X, class Y, class Z>
static auto test(int) ->
decltype( func<X>( std::declval<Y&>(), std::declval<Z const&>(), std::true_type());
template <class, class, class> static std::false_type test(...);
Run Code Online (Sandbox Code Playgroud)
并适当地测试这些功能的返回类型.由于我将pass SomeClass(Y)传递给函数,因此ADL可以让编译器查看相应的命名空间,以免被func我为测试定义的虚拟版本混淆. …