[英]Using forward declaration in a template file with type guards
我正在嘗試將模板庫中的前向聲明與類型防護結合起來,以攔截使用錯誤類型的類的錯誤模板類型的情況。 這是我可以理解的最簡單的代碼片段,目的是說明問題...
Main.cpp的
#include <iostream>
#include "templates.h"
int main()
{
B<int_array> hello;
return 0;
}
templates.h
#include <type_traits>
#define USE_GUARD
#define FORWARD_DECLARE
template<typename T>
using is_pod = typename std::enable_if<std::is_pod<T>::value>::type;
typedef struct {
int *p;
int n;
} int_array;
template <typename E, typename T >
class A
{
};
#ifdef USE_GUARD
template <typename T, typename = is_pod<typename std::remove_pointer<decltype(T::p)>::type> >
#else
template <typename T>
#endif
class B : public T, public A< B<T>, T >
{ // This is the 'curiously recurring template
// pattern' (CRTP)
public:
//! Default constructor
B() noexcept
{
T::p = nullptr;
T::n = 0;
}
#ifdef FORWARD_DECLARE
void reorder(const int_array & newOrder);
#endif
};
template <typename T> class C : public B<T>
{
public:
C() noexcept : B<T>()
{
T::p = nullptr;
T::n = 0;
}
};
#ifdef FORWARD_DECLARE
#ifdef USE_GUARD
template <typename T, typename = is_pod<typename std::remove_pointer<decltype(T::p)>::type> >
#else
template <typename T>
#endif
void B<T>::reorder(const int_array & newOrder)
{
C<T> myC;
}
#endif
我收到如下錯誤消息:
Visual Studio 2015:
既未定義USE_GUARD也未定義FORWARD_DECLARE-正常工作
僅定義FORWARD_DECLARE-可以正常工作
僅定義了USE_GUARD-可以正常工作
兩者都定義C3860: template argument lost following class template name must list parameters in the order used in template parameter list
克++:
既未定義USE_GUARD也未定義FORWARD_DECLARE-正常工作
僅定義FORWARD_DECLARE-可以正常工作
僅定義了USE_GUARD-可以正常工作
兩者均已定義-在定義函數“重新排序”時Invalid use of incomplete type 'class B<T>
”
因此,在將類型保護與正向聲明結合使用的過程中,顯然存在某些錯誤,但是沒有一個編譯器給出了非常清晰的錯誤消息。 我是在語法中犯了基本錯誤,還是只是在做一些根本上愚蠢的事情?
成員定義中不應重復使用默認參數,而應提供所有參數:
#ifdef FORWARD_DECLARE
# ifdef USE_GUARD
template <typename T, typename U>
void B<T, U>::reorder(const int_array & newOrder)
# else
template <typename T>
void B<T>::reorder(const int_array & newOrder)
# endif
{
C<T> myC;
}
#endif
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.