首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >检查可变模板参数的唯一性

检查可变模板参数的唯一性
EN

Stack Overflow用户
提问于 2013-09-24 23:59:52
回答 5查看 2.9K关注 0票数 24

我希望可变模板参数必须是唯一的。我知道当多重继承时,相同的类继承是不允许的。

代码语言:javascript
复制
struct A{};
struct B: A, A{}; // error

使用这个规则,我编写了一些代码。

代码语言:javascript
复制
#include <type_traits>

template< class T> struct id{};
template< class ...T> struct base_all : id<T> ... {};

template< class ... T>
struct is_unique
{
     template< class ... U>
 static constexpr bool test( base_all<U...> * ) noexcept { return true; }

template< class ... U>
static constexpr bool test( ... ) noexcept { return false;}


static constexpr bool value = test<T...>(0);
};

int main()
{
    constexpr bool b = is_unique<int, float, double>::value; // false -- Why?
    constexpr bool c = is_unique< int, char, int>::value; // false

   static_assert( b == true && c == false , "!");// failed.
}

但是我的程序并没有像我预期的那样工作。怎么了?

//更新://谢谢,我修复了我的错误://

代码语言:javascript
复制
//     #include <type_traits>
//     #include <cstddef>
//    
//     template< class ... U> struct pack{};
//    
//     template< class T> struct id{};
//     template< class T> struct base_all;
//     template< class ... T> struct base_all< pack<T...> > : id<T>  ... {};
//        
//     
//    
//     template< class ... T>
//     struct is_unique
//     {
//           template< class P,  std::size_t  =  sizeof(base_all<P>) >
//          struct check;
//     
//       template< class ...U>
//      static constexpr bool test(check< pack<U...> > * ) noexcept { return true;}
//        
//        template< class ... U>
//        static constexpr bool test(...)noexcept { return false;}
//        
//        static constexpr bool value =  test<T...>(0);
//        };
//        
//        int main()
//        {
//            constexpr bool b = is_unique<int, float, double>::value; // true
//            constexpr bool c = is_unique< int, char, int>::value; // false
//             
//          static_assert( b == true && c == false , "!");// success.
//        }
//

问:有人可以解释一下,为什么它失败了?

UPDATE2:我之前的更新是非法的:))。合法形式,但编译时间为O(N)。

代码语言:javascript
复制
#include <cstddef>
#include <iostream>
#include <type_traits>

namespace mpl
{

template< class T > using invoke = typename T :: type ;

template< class C, class I, class E > using if_t     = invoke< std::conditional< C{}, I, E> >;

template< class T > struct id{};
struct empty{};

template< class A, class B > struct base : A, B {};

template< class B , class ... > struct is_unique_impl;

template< class B > struct is_unique_impl<B>: std::true_type{};

template< class B, class T, class ... U>
struct is_unique_impl<B, T, U...> : if_t< std::is_base_of< id<T>, B>, std::false_type, is_unique_impl< base<B,id<T>>, U...> >{};


template< class ...T >struct is_unique : is_unique_impl< empty, T ... > {};



} // mpl    

int main()
{
    constexpr bool b = mpl::is_unique<int, float, double>::value;

    constexpr bool c = mpl::is_unique< int, char, int > :: value;

    static_assert( b == true   , "!");
    static_assert( c == false, "!");

    return 0;

}
EN

回答 5

Stack Overflow用户

发布于 2013-09-25 00:43:55

传递一个指向base_all<U...>的指针只需要存在一个base_all<U...>声明。如果不尝试访问定义,编译器将不会检测到该类型实际上是错误定义的。缓解该问题的一种方法是使用需要定义base_all<U...>的参数,例如:

代码语言:javascript
复制
template< class ...T> struct base_all
   : id<T> ...
{
    typedef int type;
};
// ...
template< class ... U>
static constexpr bool test(typename base_all<U...>::type) noexcept
{
    return true;
}

尽管上面回答了这个问题,但它无法编译:创建的多重继承不在适合SFINAE的上下文中。我不认为你可以利用不允许从两次继承的相同基础的规则。不过,可以以不同的方式实现相关的测试:

代码语言:javascript
复制
#include <type_traits>

template <typename...>
struct is_one_of;

template <typename F>
struct is_one_of<F>
{
    static constexpr bool value = false;
};

template <typename F, typename S, typename... T>
struct is_one_of<F, S, T...>
{
    static constexpr bool value = std::is_same<F, S>::value
        || is_one_of<F, T...>::value;
};

template <typename...>
struct is_unique;

template <>
struct is_unique<> {
    static constexpr bool value = true;
};

template<typename F, typename... T>
struct is_unique<F, T...>
{
    static constexpr bool value = is_unique<T...>::value
        && !is_one_of<F, T...>::value;
};

int main()
{
    constexpr bool b = is_unique<int, float, double>::value;
    constexpr bool c = is_unique< int, char, int>::value;
    static_assert( b == true && c == false , "!");
}
票数 12
EN

Stack Overflow用户

发布于 2013-09-27 19:52:06

另一个O(logN)实例化深度解决方案。它仍然需要主要的清理、注释、名称空间、重命名和减少代码重复。

再次向Xeo致敬,这(再次)依赖于它的O(logN) instantiation depth version of gen_seq

代码语言:javascript
复制
#include <cstddef>

    // using aliases for cleaner syntax
    template<class T> using Invoke = typename T::type;

    template<std::size_t...> struct seq{ using type = seq; };

    template<class S1, class S2> struct concat;

    template<std::size_t... I1, std::size_t... I2>
    struct concat<seq<I1...>, seq<I2...>>
      : seq<I1..., (sizeof...(I1)+I2)...>{};

    template<class S1, class S2>
    using Concat = Invoke<concat<S1, S2>>;

    template<std::size_t N> struct gen_seq;
    template<std::size_t N> using GenSeq = Invoke<gen_seq<N>>;

    template<std::size_t N>
    struct gen_seq : Concat<GenSeq<N/2>, GenSeq<N - N/2>>{};

    template<> struct gen_seq<0> : seq<>{};
    template<> struct gen_seq<1> : seq<0>{};

除了索引序列生成之外,这个解决方案甚至应该具有O(1)实例化深度。它使用std::array<std::false_type, size>来执行O(1)实例化深度OR,而不是多重继承。

is_one_of的实现。请注意,“是其中之一”是“唯一的”的相反概念。

代码语言:javascript
复制
#include <array>

// check if `T` is in `Us...`
template<class T, class... Us>
struct is_one_of
{
    template<class T1>
    static constexpr auto SFINAE(int)
    -> decltype( std::array<std::false_type, sizeof...(Us)>
                 {{std::is_same<T1, Us>{}...}} )
    {  return {}; /* only to suppress warning */  }

    template<class...>
    static constexpr int SFINAE(...) { return 42; }

    template<class T1>
    static constexpr bool test()
    {
        return std::is_same<decltype(SFINAE<T1>(0)), int>{};
    }

    static constexpr bool value = test<T>();
    constexpr operator bool() const { return value; }
};

are_unique的实现

代码语言:javascript
复制
namespace detail
{
    // `Any` type with a generic no-constraint ctor
    // to discard a number of arguments for a function template
    template<std::size_t>
    struct Any
    {
        template<class T>
        constexpr Any(T&&) {}
    };

    // `wrapper` is used as a substitute for `declval`,
    // and can keep track if `T` is a reference
    template<class T>
    struct wrapper { using type = T; };

    template<std::size_t I, class T, class... Us>
    struct is_one_of_pack
    {
        template<std::size_t... I1s>
        struct helper
        {
            template<class... Remaining>
            static constexpr bool deduce_remaining(Any<I1s>..., Remaining...)
            {
                // unique <-> is one of
                return not is_one_of<T, typename Remaining::type...>{};
            }
        };

        template<std::size_t... I1s>
        static constexpr bool deduce_seq(seq<I1s...>)
        {
            return helper<I1s...>::template deduce_remaining(wrapper<Us>()...);
        }

        static constexpr bool create_seq()
        {
            return deduce_seq(gen_seq<I+1>{});
        }

        using type = std::integral_constant<bool, create_seq()>;
    };

    template<class... Packs>
    constexpr auto SFINAE(int)
    -> decltype( std::array<std::true_type, sizeof...(Packs)>
                 {{typename Packs::type{}...}} )
    {  return {}; /* only to suppress warning */  }

    template<class...>
    static constexpr int SFINAE(...) { return 42; }

    template<class... Packs>
    constexpr bool test()
    {
        return std::is_same<decltype(SFINAE<Packs...>(0)), int>{};
    }

    template<class... Ts, std::size_t... Is>
    constexpr bool deduce_seq(seq<Is...>)
    {
        return test< is_one_of_pack<Is, Ts, Ts...>... >();
    }
}

template<class... Ts>
struct are_unique
: std::integral_constant<bool,
                         detail::deduce_seq<Ts...>(gen_seq<sizeof...(Ts)>{})>
{};

使用示例:

代码语言:javascript
复制
#include <iostream>
#include <iomanip>
int main()
{
    bool a = are_unique<bool, char, int>();
    bool b = are_unique<bool, char, int, bool>();
    bool c = are_unique<bool, char, bool, int>();
    std::cout << std::boolalpha;
    std::cout << a << std::endl;
    std::cout << b << std::endl;
    std::cout << c << std::endl;
}
票数 3
EN

Stack Overflow用户

发布于 2020-01-04 03:03:54

使用C++17,您可以使用折叠表达式。特别是在模板参数数量更多的情况下,此版本的速度可以比此处提供的其他解决方案快几个数量级(并且占用的内存更少):

代码语言:javascript
复制
#include <type_traits>

template <typename T> 
struct Base{};

template <typename... Ts>
struct TypeSet : Base<Ts>...
{     
   template<typename T>
   constexpr auto operator+(Base<T>)
   {
      if constexpr (std::is_base_of_v<Base<T>, TypeSet>)
        return TypeSet{};
      else
        return TypeSet<Ts..., T>{};
   }

   constexpr auto size() const -> std::size_t
   {
      return sizeof...(Ts);
   }
};

template<typename... Ts>
constexpr auto are_unique() -> bool
{ 
   constexpr auto set = (TypeSet<>{} + ... + Base<Ts>{});
   return set.size() == sizeof...(Ts);
}

int main()
{
   static_assert(are_unique<int, float, char, char*>());
   static_assert(not are_unique<int, float, char, char>());
}

请参阅https://godbolt.org/z/_ELpyJ

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/18986560

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档