[英]Forward Declaration using for a template method
為什么在使用帶有前向聲明 class 的模板方法時會出現錯誤? 我實際上不需要這個 class 的定義,只需要一個聲明。 或者也許我誤解了它的實際工作原理? 我真的需要包含 class B
的相應.h 文件嗎?
編輯:如果我實際上包含“Bh”,為什么 class SomeInterface 的前向聲明與static_assert
一起工作?
我想實現前向聲明以使用模板方法而不包含“.h”文件
凱文回復后的問題:
bar() 方法實際上是模板方法模式所需要的,因此會有類似命名空間的系列 Second。 問題是,如果我從命名空間第二個中包含更多“.h”文件,它的優化程度是否會降低? 此 bar() 方法只會在程序開始時執行一次
示例代碼:
// A.cpp
#include "A.h"
namespace Second
{
class SomeInterface;
class B;
}
namespace First
{
class A
{
public:
A() = default;
template <typename M>
void foo()
{
static_assert(std::is_base_of<Second::SomeInterface, M>::value, "You need to use SomeInterface or Derived from it");
}
void bar() // -- Template Method Pattern
{
foo<Second::B>(); // -- C2139 'Second::B': an undefined class is not allowed as
// an argument to compiler intrinsic type trait '__is_base_of'
foo<Second::C>();
foo<Second::D>();
//...
}
};
}
// B.cpp
#include "B.h"
#include "SomeInerface.h"
namespace Second
{
class B : public SomeInterface
{
public:
B() = default;
};
}
如果我將其添加到 A.cpp 中,它將正常工作
#include "B.h"
為什么在使用帶有前向聲明 class 的模板方法時會出現錯誤?
這通常不是問題。
我實際上不需要這個 class 的定義,只需要一個聲明。 或者也許我誤解了它的實際工作原理?
沒有模板參數必須是完整類型的一般規則,但有特定的情況,你的就是其中之一。
我真的需要包含一個對應的 class B 的.h 文件嗎?
在這種情況下,是的。
為什么前向聲明與 static_assert 一起工作?
我不確定你是什么意思。 代碼中唯一的static_assert
位於模板方法First::A::foo()
中。 當您使用某個模板參數實例化模板時,您會收到與該static_assert
相關的錯誤(盡管不是斷言失敗)。 那么,在什么意義上,您認為static_assert
的行為不一致?
這里的基本問題是std::is_base_of
模板要求它的第二個類型參數是一個完整的類型。 這在其規格中。 class 類型(僅)向前聲明,在 scope 中沒有定義,是不完整的。 因此,當您在 scope 中沒有定義Second::B
的位置實例化First::A::foo<Second::B>
時,會出現錯誤。在評估斷言之前會識別出該錯誤,因此static_assert
不考慮 except 作為錯誤的上下文。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.