鍍金池/ 問答/C++/ 造is_base_of輪子時(shí)候發(fā)現(xiàn)的一個(gè)問題

造is_base_of輪子時(shí)候發(fā)現(xiàn)的一個(gè)問題

我嘗試著去實(shí)現(xiàn)一個(gè)naive的is_base_of(沒考慮健壯性,is_class等等),這個(gè)版本被static_assert證明是可行的。

template
<typename T>
struct _IsBaseOfBase {
    constexpr static bool Testment(T* t)
    {
        return true;
    }

    constexpr static bool Testment(...)
    {
        return false;
    }
};

template
<typename T, typename U>
struct IsBaseOf {
    constexpr static bool value = _IsBaseOfBase<T>::Testment(static_cast<U*>(nullptr));
};

然而這個(gè)版本卻被VS的static_assert提示"表達(dá)式必須含有常量值"

template
<typename T, typename U>
struct IsBaseOf {
    constexpr static bool Testment(T* t)
    {
        return true;
    }

    constexpr static bool Testment(...)
    {
        return false;
    }

    constexpr static bool value = IsBaseOf<T,U>::Testment(static_cast<U*>(nullptr));
};

想請(qǐng)教一下出錯(cuò)的原因?

回答
編輯回答
哎呦喂
  • Because msvc's support for constexpr is a shit. When static_assert see IsBaseOf<A, B>::value, it is not regarded as const expression: http://rextester.com/ATOC6638
  • So, it is not your fault, just msvc's bug. You can test your codes on gcc/clang, both will compile happily :http://rextester.com/IWU81465
2017年6月28日 18:30