接受C++中的任何类型的参数。

huangapple go评论57阅读模式
英文:

Accept Any type of argument in cpp

问题

我想要一个函数,可以接受任何类型的参数,然后在实现中可以检查类型是否为整数,然后可以抛出一条消息。例如,函数可以像下面这样调用:

add(10, 12);
输出: "正确的输入。相加得到22"
add(10, "hello");
输出: "错误的输入"
add(10);
输出: "错误的输入!缺少参数"

在C++中是否有可能实现这一点?

使用重载,我将不得不创建所有可能组合的函数,比如(int,double),(double,int),(int,string),(string,int)等等,是否还有其他方法?

英文:

I want a function that can accept any type of argument and then in the implementation, can check if the type is integer and then can throw a message. For example the function can be called like the following,

add(10, 12);
Output : "correct input. addition is 22"

add(10, "hello")
Output : "wrong input"
add(10)
Output : "wrong input! missing arguments"

Is it possible to achieve this in C++?

Using overloading I will have to create functions of all possible combination such as (int, double), (double, int), (int, string), (string, int) and so on, so is there any other way?

答案1

得分: 3

Since C++17, you can use std::any and std::any_cast:

#include <any>
#include <iostream>

void add(const std::any& a = "", const std::any& b = "")
{
    try {
        const int ia = std::any_cast<int>(a);
        const int ib = std::any_cast<int>(b);

        std::cout << "correct input. addition is " << ia + ib << std::endl;
    }
    catch (...) {
        std::cout << "wrong input" << std::endl;
    }
}

int main()
{
    add(10, "hello");
    add(10, 12);
    add(10);
    add();
}

Demo

A pre-C++17 solution:

#include <iostream>

void add(int a, int b)
{
    std::cout << "correct input. addition is " << a + b << std::endl;
}

template<typename... Ts>
void add(Ts...)
{
    std::cout << "wrong input" << std::endl;
}

int main()
{
    add(10, "hello");
    add(10, 12);
    add(10);
    add();
}

Demo

英文:

Since C++17, you can use std::any and std::any_cast:

#include &lt;any&gt;
#include &lt;iostream&gt;

void add(const std::any&amp; a = &quot;&quot;, const std::any&amp; b = &quot;&quot;)
{
	try {
		const int ia = std::any_cast&lt;int&gt;(a);
		const int ib = std::any_cast&lt;int&gt;(b);

		std::cout &lt;&lt; &quot;correct input. addition is &quot; &lt;&lt; ia + ib &lt;&lt; std::endl;
	}
	catch (...) {
		std::cout &lt;&lt; &quot;wrong input&quot; &lt;&lt; std::endl;
	}
}

int main()
{
	add(10, &quot;hello&quot;);
	add(10, 12);
	add(10);
	add();
}

Demo


A pre-C++17 solution:

#include &lt;iostream&gt;

void add(int a, int b)
{
	std::cout &lt;&lt; &quot;correct input. addition is &quot; &lt;&lt; a + b &lt;&lt; std::endl;
}

template&lt;typename... Ts&gt;
void add(Ts...)
{
	std::cout &lt;&lt; &quot;wrong input&quot; &lt;&lt; std::endl;
}

int main()
{
	add(10, &quot;hello&quot;);
	add(10, 12);
	add(10);
	add();
}

Demo

答案2

得分: 1

以下是翻译好的部分:

第一件事是编写一个重载函数,接受精确的两个整数:

void add(int a, int b) {
    std::cout << "正确的输入。答案是 " << a + b << "\n";
}

一般来说,这就足够了。如果使用不正确数量的参数进行调用,或者使用不能转换为 int 的两个参数进行调用,编译器会为您生成错误。

如果您不希望出现错误,而是想在运行时打印错误消息,您可以添加更多的重载。正如您已经注意到的,为明确的类型添加重载并不会起作用,但您可以添加一个通用函数(函数模板),它将接受任何类型:

void add(auto ...) {
    std::cout << "输入不正确\n";
}

请注意,在C++20之前,函数模板的声明应该如下:

template<typename ...Ts>
void add(Ts ...);

如果您想要更具体的错误消息,可以继续添加更多的重载,例如,对于只传递一个参数的调用:

void add(auto) {
    std::cout << "参数不足\n";
}

这里有一个演示

英文:

The first thing to do is write an overload that accepts exactly 2 ints:

void add(int a, int b) {
    std::cout &lt;&lt; &quot;Correct input. Answer is &quot; &lt;&lt; a + b &lt;&lt; &quot;\n&quot;;
}

And that should generally be enough. If a call is made with an incorrect number of arguments, or with 2 arguments that can't be converted to int, the compiler will produce an error for you.

If you don't want an error, but instead want to print an error message at runtime, you can just add overloads. As you've noticed, adding overloads for explicit types isn't really going to work, but you can add a generic function (a function template) that will accept anything:

void add(auto ...) {
    std::cout &lt;&lt; &quot;Incorrect input\n&quot;;
}

Note that pre-C++20, the signature has to be spelled

template&lt;typename ...Ts&gt;
void add(Ts ...);

You can continue adding more overloads if you want more specific error messages, e.g. for a call where only one argument is passed:

void add(auto) {
    std::cout &lt;&lt; &quot;Insufficient arguments\n&quot;;
}

Here's a demo.

huangapple
  • 本文由 发表于 2023年2月19日 00:59:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/75494903.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定