2013-09-27 60 views
1

我在這裏發佈關於檢查唯一性的可變參數模板參數 check variadic templates parameters for uniquenesscheck-variadic-templates-parameters-for-uniqueness2

我的問題:爲什麼下面的代碼沒有編譯?它是bug編譯器還是標準不允許?

#include <iostream> 


template< class ... > struct pack{}; 
template<class> struct id{}; 
template<class> struct base_all; 
template< class ...T> 
struct base_all< pack<T...> > : id<T> ... {using type = int;}; // <-- error with `int`, `char`, `int` parameters. 

template< class ...T> 
struct is_unique 
{ 
    template< class P, std::size_t = sizeof(base_all<P>) > 
    struct check; 

    template< class P > 
    static constexpr bool test(check<P> *) noexcept { return true ;} 

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

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

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

    constexpr bool c = is_unique<int, char, int >::value; //<--- error 

    std::cout << std::boolalpha << "b = " << b << "\nc = " << c << std::endl; 
} 

錯誤編譯器GCC 4.8.1:

is_unique_args.cpp:16:42: required by substitution of ‘template<class P> static constexpr bool is_unique<T>::test(is_unique<T>::check<P>*) [with P = P; T = {int, char, int}] [with P = pack<int, char, int>]’ 
+0

SFINAE只考慮直接上下文,基本上所有在功能站點「可見」(你可以看到)的所有東西,以及「使用」別名內的東西。無效的基礎成員不計數,這是一個間接的錯誤。 – Xeo

+2

@ g-makulik。它不是重複的,它是連續的...)) –

+0

好的!我看到你似乎有了一些進步(不過,我已經編輯和更新了原始問題,也許開始了一個賞金)。我不確定這是否對你有任何幫助,最近我一直在問一個問題:如何在編譯時處理一個'std :: tuple'參數包來做一些計算:[從數據庫創建一個數組初始值設定項元組或變量模板參數](http://stackoverflow.com/questions/18251815/creating-an-array-initializer-from-a-tuple-or-variadic-template-parameters)。可能這會給你一個方向。 –

回答

1

我編譯你的例子是這樣的:

g++ -Wall -Wextra -std=c++11 -rdynamic -pedantic garbage.cpp 

,並得到了不同的錯誤:

garbage.cpp: In instantiation of ‘struct base_all<pack<int, char, int> >’: 
garbage.cpp:17:27: required by substitution of ‘template<class P> static constexpr bool is_unique::test(is_unique<T>::check<P>*) [with P = P; T = {int, char, int}] [with P = pack<int, char, int>]’ 
garbage.cpp:22:63: required from ‘constexpr const bool is_unique<int, char, int>::value’ 
garbage.cpp:29:52: required from here 
garbage.cpp:8:8: error: duplicate base type ‘id<int>’ invalid 

爲了突出錯誤再次發生:

重複的基本類型「ID」無效

這是非常清楚這意味着什麼。 C++禁止擁有更多相同類型的基類。所以,這是標準所禁止的:

struct A 
{}; 
struct B : A, A 
{}; 

這就是你上面要做的。

+0

我認爲這是OP試圖用SFINAE檢查前端的內容。 –

+0

@ g-makulik是的,但他嘗試的方式並不奏效。我解釋了爲什麼 –

+0

這就是爲什麼我一直在upvoting;) –