代码之家  ›  专栏  ›  技术社区  ›  ryancheung

实例化后“CheckIntMap<>”的显式专门化

  •  4
  • ryancheung  · 技术社区  · 8 年前
    template<typename... U> constexpr int CheckIntMap(const char *szStr, int nDefaultInt, const char *szOptStr1, int nOptInt1, U&&... u)
    {
        return (CheckIntMap(szStr, nDefaultInt, szOptStr1, nOptInt1) == nOptInt1) ? nOptInt1 : CheckIntMap(szStr, nDefaultInt, std::forward<U>(u)...);
    }
    
    template<> constexpr int CheckIntMap(const char *szStr, int nDefaultInt, const char *szOptStr1, int nOptInt1)
    {
        return CompareUTF8(szStr, szOptStr1) ? nOptInt1 : nDefaultInt;
    }
    

    叮当声:

    Apple LLVM version 9.0.0 (clang-900.0.39.2)
    Target: x86_64-apple-darwin17.3.0
    Thread model: posix
    InstalledDir: /Library/Developer/CommandLineTools/usr/bin
    Found CUDA installation: /usr/local/cuda, version 7.0
    

    编译错误:

    /Users/xxx/xxx/xxxx/common/src/constexprfunc.hpp:58:30: error: explicit specialization of 'CheckIntMap<>' after instantiation
        template<> constexpr int CheckIntMap(const char *szStr, int nDefaultInt, const char *szOptStr1, int nOptInt1)
                                 ^
    /Users/xxx/xxx/xxxx/common/src/constexprfunc.hpp:55:17: note: implicit instantiation first required here
            return (CheckIntMap(szStr, nDefaultInt, szOptStr1, nOptInt1) == nOptInt1) ? nOptInt1 : CheckIntMap(szStr, nDefaultInt, std::forward<U>(u)...);
    

    此代码在g++5.4(linux)中编译

    我怎样才能解决这个问题。

    1 回复  |  直到 8 年前
        1
  •  4
  •   songyuanyao    8 年前

    您可以将专门化声明移到需要隐式实例化的位置之前。例如

    // declarations
    template<typename... U> constexpr int CheckIntMap(const char *szStr, int nDefaultInt, const char *szOptStr1, int nOptInt1, U&&... u);
    template<> constexpr int CheckIntMap(const char *szStr, int nDefaultInt, const char *szOptStr1, int nOptInt1);
    
    // definitions
    template<typename... U> constexpr int CheckIntMap(const char *szStr, int nDefaultInt, const char *szOptStr1, int nOptInt1, U&&... u)
    {
        return (CheckIntMap(szStr, nDefaultInt, szOptStr1, nOptInt1) == nOptInt1) ? nOptInt1 : CheckIntMap(szStr, nDefaultInt, std::forward<U>(u)...);
    }
    
    template<> constexpr int CheckIntMap(const char *szStr, int nDefaultInt, const char *szOptStr1, int nOptInt1)
    {
        return CompareUTF8(szStr, szOptStr1) ? nOptInt1 : nDefaultInt;
    }