(有些)过时的文章探讨了decltype与SFINAE一起使用的方法,以检测某种类型是否支持某些运算符,例如==或<.
以下是检测类是否支持<运算符的示例代码:
template <class T>
struct supports_less_than
{
static auto less_than_test(const T* t) -> decltype(*t < *t, char(0))
{ }
static std::array<char, 2> less_than_test(...) { }
static const bool value = (sizeof(less_than_test((T*)0)) == 1);
};
int main()
{
std::cout << std::boolalpha << supports_less_than<std::string>::value << endl;
}
Run Code Online (Sandbox Code Playgroud)
这输出true,因为当然std::string支持<操作员.但是,如果我尝试将它与不支持<运算符的类一起使用,我会收到编译器错误:
error: no match for ‘operator<’ in ‘* t < * t’
Run Code Online (Sandbox Code Playgroud)
所以SFINAE不在这里工作.我在GCC 4.4和GCC …
在使用编译时字符串(可变参数列表char)操作时,我需要实现一种检查编译时字符串是否包含另一个(较小的)编译时字符串的方法.
这是我的第一次尝试:
template<int I1, int I2, typename, typename> struct Contains;
template<int I1, int I2, char... Cs1, char... Cs2>
struct Contains<I1, I2, CharList<Cs1...>, CharList<Cs2...>>
{
using L1 = CharList<Cs1...>;
using L2 = CharList<Cs2...>;
static constexpr int sz1{L1::size};
static constexpr int sz2{L2::size};
using Type = std::conditional
<
(I1 >= sz1),
std::false_type,
std::conditional
<
(L1::template at<I1>() != L2::template at<I2>()),
typename Contains<I1 + 1, 0, L1, L2>::Type,
std::conditional
<
(I2 == sz2 - 1),
std::true_type,
typename Contains<I1 + 1, I2 + 1, …Run Code Online (Sandbox Code Playgroud) c++ templates metaprogramming template-meta-programming c++14
我如何懒惰评估std :: conditional中的第二个arg?
#include "stdafx.h"
#include <type_traits>
struct Null{};
struct _1{enum {one = true,two = false};};
struct _2{enum {two = true, one = false};};
template<class T>
struct is_nulltype
{
enum {value = false};
};
template<>
struct is_nulltype<Null>
{
enum {value = true};
};
template<class T>
struct X : std::conditional<is_nulltype<T>::value,Null,typename std::conditional<T::one,_1,_2>::type>::type
{
};
int _tmain(int argc, _TCHAR* argv[])
{
X<Null> x;//won't compile no Null::one but I don't need that member in Null at all
return 0;
}
Run Code Online (Sandbox Code Playgroud)