我在coliru.stacked-crooked.com上有以下工作代码。
正如static std::false_type check(...)
重复的那样,我想知道我们是否可以分解它。例如在基类中。正如Jonathan Wakely所指出的,我在问题底部的尝试使用 Clang 编译,但不使用 GCC。
我尝试了很多可能性,但似乎无法decltype
使用 GCC 来继承模板静态函数。
问题:
1. GCC-4.9 在这一点上是否符合 C++11 标准?
2.在继承的模板静态成员函数上使用符合 GCC 的解决方法是什么?decltype
#include <type_traits>
#include <iostream>
#include <string>
template<typename T>
struct is_addable
{
template<typename U> static std::false_type check(...);
template<typename U> static auto check(int)
-> decltype( std::declval<U>() + std::declval<U>(), std::true_type{});
using type = decltype(check<T>(0));
};
template<typename T>
struct is_multiplicable
{
template<typename U> static std::false_type check(...);
template<typename U> static auto check(int)
-> decltype( std::declval<U>() * std::declval<U>(), std::true_type{});
using type = decltype(check<T>(0));
};
int main()
{
std::cout <<"is_addable\n";
std::cout <<" long: "<< is_addable<long>::type::value <<'\n';
std::cout <<" string: "<< is_addable<std::string>::type::value <<'\n';
std::cout <<" void: "<< is_addable<void>::type::value <<'\n';
std::cout <<"is_multiplicable\n";
std::cout <<" long: "<< is_multiplicable<long>::type::value <<'\n';
std::cout <<" string: "<< is_multiplicable<std::string>::type::value <<'\n';
std::cout <<" void: "<< is_multiplicable<void>::type::value <<'\n';
}
我的尝试之一
编辑:如Jonathan Wakelytemplate<typename U>
所指出的那样添加
struct default_check
{
template<typename U>
static std::false_type check(...);
};
template<typename T>
struct is_addable : default_check
{
using default_check::check;
template<typename U> static auto check(int)
-> decltype( std::declval<U>() + std::declval<U>(), std::true_type{});
using type = decltype(check<T>(0));
};
GCC-4.9.2 在coliru.stacked-crooked.com上失败
> g++ -std=c++11 -Wall -pedantic -Wextra -Wfatal-errors main.cpp
main.cpp: In instantiation of 'struct is_addable<void>':
main.cpp:38:63: required from here
main.cpp:19:30: error: no matching function for call to 'is_addable<void>::check(int)'
using type = decltype(check<T>(0));
^
compilation terminated due to -Wfatal-errors.
Clang-3.4.1 在godbolt.org上成功
> clang++ -std=c++11 -Wall -pedantic -Wextra -Wfatal-errors