如果不故意使用未使用的参数,如何避免出现警告?

时间:2019-02-15 11:40:53

标签: c++

假设我有一种算法,可以在执行昂贵的计算之前对其参数进行廉价的测试:

struct no_test
{
    template<typename T1, typename T2> 
    static bool applies(T1 const& t1, T2 const& t2)
    {
        return true;
    }
};

struct some_test 
{
    template<typename T1, typename T2> 
    static bool applies(T1 const& t1, T2 const& t2)
    {
        return t1  < t2; 
    }
};

template<typename T1, typename T2, typename Test = no_test> 
void some_algorithm(T1 const& t1, T2 const& t2)
{
    if (Test::applies(t1, t2))
    {
        // Do some work. 
    }
}

int main()
{
    some_algorithm(1.0, 2); 
}

如果使用-Wunused-parametergcc编译此代码,则会生成警告:

main.cpp:4:35: warning: unused parameter ‘t1’ [-Wunused-parameter]
     static bool applies(T1 const& t1, T2 const& t2)
                         ~~~~~~~~~~^~
main.cpp:4:49: warning: unused parameter ‘t2’ [-Wunused-parameter]
     static bool applies(T1 const& t1, T2 const& t2)

但是在这种情况下,no_test不是故意使用t1t2,因为如果我不希望some_algorithm执行测试,{{1可以使用}},因为它总是返回true。

对于我的其余代码,如果不使用函数参数,我想输出警告。

1 个答案:

答案 0 :(得分:2)

只需删除参数名称:

static bool applies(T1 const& , T2 const& )
{
    return true;
}