亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

模板約束C ++

模板約束C ++

C++
DIEA 2019-11-13 16:11:05
在C#中,我們可以定義一個通用類型,該通用類型對可用作通用參數的類型施加了約束。以下示例說明了通用約束的用法:interface IFoo{}class Foo<T> where T : IFoo{}class Bar : IFoo{}class Simpson{}class Program{    static void Main(string[] args)    {        Foo<Bar> a = new Foo<Bar>();        Foo<Simpson> b = new Foo<Simpson>(); // error CS0309    }}有沒有一種方法可以對C ++中的模板參數施加約束。C ++ 0x為此提供了本機支持,但是我正在談論當前的標準C ++。
查看完整描述

3 回答

?
FFIVE

TA貢獻1797條經驗 獲得超6個贊

您可以在不執行任何操作的IFoo上放置一個保護類型,確保它在Foo中的T上存在:


class IFoo

{

public:

    typedef int IsDerivedFromIFoo;

};


template <typename T>

class Foo<T>

{

    typedef typename T::IsDerivedFromIFoo IFooGuard;

}


查看完整回答
反對 回復 2019-11-13
?
繁華開滿天機

TA貢獻1816條經驗 獲得超4個贊

如果使用C ++ 11,則可以使用static_assertwith std::is_base_of來實現此目的。


例如,


#include <type_traits>


template<typename T>

class YourClass {


    YourClass() {

        // Compile-time check

        static_assert(std::is_base_of<BaseClass, T>::value, "type parameter of this class must derive from BaseClass");


        // ...

    }

}


查看完整回答
反對 回復 2019-11-13
  • 3 回答
  • 0 關注
  • 552 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號