c ++用可变参数模板替换Var Args

问题描述 投票:0回答:1

我正在使用带有模板和递归的C ++ 17来替换C Va_Args。当前仅支持浮点数,一旦浮点数起作用,就会有更多类型;)

class CWrite
{
public:
    template<typename NextT, typename ...RestT>
    static std::string Format(NextT next, RestT ... rest);

private:

    template<typename T>
    static constexpr bool is_float = std::is_same_v<T, float>;

    template<typename T>
    static constexpr bool IsValidParam();

    template<typename LastT>
    static std::string Format(LastT last);

    ///Empty param case
    static std::string Format();

};

// +++++++++++++++++++  Implementation ++++++++++++++++++++++++++

template<typename T>
constexpr bool CWrite::IsValidParam()
{
    bool bRes = false;
    bRes |= is_float<T>;
    return bRes;
}

template<typename NextT, typename ...RestT>
std::string CWrite::Format(NextT next, RestT ... rest)
{
    std::string strRes = Format(next);
    strRes += Format(rest...);
    return strRes;
}

template<typename LastT>
std::string CWrite::Format(LastT last)
{

    std::string strRes;
    if (is_float<LastT>)
    {
        strRes = "float:";
        char buffer[10] = { };
        snprintf(buffer, 10, "%f", last);
        strRes += buffer;
    }

    return strRes;
}

///Empty param case
std::string CWrite::Format()
{
    return "";
}

与此通话

std::string strRes = CWrite::Format(1.0f, 2.0f, 3.0f, 4.0f, 5);

结果为s​​nprintf警告格式'%f'期望参数类型为'double',但是参数4的类型为'int'

我希望IsValidParam对于应该为整数的最后一个参数返回false。

https://onlinegdb.com/B1A72GHgU

您能帮我吗?我在这里想念什么吗?

c++ templates variadic-functions
1个回答
0
投票

如果可以使用C ++ 17,则应在以下功能中使用if constexpr

© www.soinside.com 2019 - 2024. All rights reserved.